<!-- 非项目付款合同流程编辑 -->
<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
      	fontSize: '14px',
      	color: '#B2B2B2',
      	lineHight: '20px'
      }"
    >
    	<view class="basic-style">
    	  <view class="basic-title basic-border pt-1">供方信息</view>
    	  <u-form-item label="供应商名称" prop="supplyCompanName" required>
    	    <h-select-customer-input-popup
						disabled
    	      style="width: 100%"
    	      commercialType="2"
						:isJudge='true'
						@onJudge='onJudge'
    	      v-model="model.supplyCompanName"
    	      border="surround"
    	      placeholder="请选择供应商名称"
    	      suffixIcon="arrow-down-fill"
    	      :suffixIconStyle="{ color: '#B2B2B2' }"/>
    		<!-- <u-icon style="margin-left: 10upx;" name="plus" color="#2979ff" size="24" @click="getUnSupplier"/> -->
    	  </u-form-item>
    	  <u-form-item label="公司地址" prop="supplyCompanyAddress" required>
    	    <u--input placeholder="请输入公司地址" disabled v-model="model.supplyCompanyAddress" />
    	  </u-form-item>
    	  <u-form-item label="委托代理人" prop="supplyEntrustedAgent" required>
    	    <u--input placeholder="请输入委托代理人" disabled v-model="model.supplyEntrustedAgent" />
    	  </u-form-item>
    	  <u-form-item label="手机号码" prop="supplyPhoneNumber" required>
    	    <u--input type="number" disabled placeholder="请输入手机号码" v-model="model.supplyPhoneNumber" />
    	  </u-form-item>
    	  <u-form-item label="开户银行" prop="supplyBankName" required>
    	    <u--input disabled placeholder="请输入开户银行" v-model="model.supplyBankName" />
    	  </u-form-item>
    	  <u-form-item label="银行账号" prop="supplyBankAccountNo" required>
    	    <u--input disabled placeholder="请输入银行账号" v-model="model.supplyBankAccountNo" />
    	  </u-form-item>
    	  <u-form-item label="纳税人识别号" prop="supplyRegistrationNumber" required>
    	    <u--input disabled placeholder="请输入纳税人识别号" v-model="model.supplyRegistrationNumber" />
    	  </u-form-item>
    	</view>
    	
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
        <u-form-item label="单据编号" prop="purchaseBill" required>
          <u--input v-model="model.purchaseBill" disabled></u--input>
        </u-form-item>
        <u-form-item label="申请人" prop="propose" required>
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.proposer"
            placeholder="请选择申请人"
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.proposer"
          ></h-select-person-input>
        </u-form-item>
				<u-form-item label="申请时间" required>
				  <u--input v-model="model.createTime" disabled placeholder="请重新生成申请时间"></u--input>
				</u-form-item>
        <u-form-item label="申请部门" prop="proposerDeptId" required>
          <h-select-depart-input
            disabled
            v-model="model.proposerDeptId"
            :departName="model.proposerDeptText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.proposerDeptText"
          ></h-select-depart-input>
        </u-form-item>
				<u-form-item label="申请人所属团队" prop="applyTeam" required>
					<h-select-team-input-popup
						disabled
						style="width: 100%"
						v-model="model.applyTeam"
						placeholder="请选择申请人所属团队"
						:tdlx="1"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
					></h-select-team-input-popup>
				</u-form-item>
        <u-form-item label="合同名称" prop="contractName" required>
          <u--input v-model="model.contractName" disabled placeholder="请输入合同名称"></u--input>
        </u-form-item>
    		<u-form-item label="采购类型" prop="procurementType" required>
    			<h-select-input-tag
    			  class="w-100"
						disabled
    			  v-model="model.procurementType"
    			  placeholder="请选择采购类型"
    			  border="surround"
    			  dictName="procurement_type"
    				suffixIcon="arrow-down-fill"
    				:suffixIconStyle="{ color: '#B2B2B2' }"
    			  @change="handleChangeProvisionType"
    			></h-select-input-tag>
    		</u-form-item>
    		
    		<view v-show="model.procurementType == '1'">
    		  <u-form-item label="关联单据" prop="associationBillId" required>
    		    <h-select-purchase-calibration-input-popup
							disabled
    		      :projectId="model.xmmc"
    		      v-model="model.associationBillId"
    					allowExistAll="yes"
    		      placeholder="请关联定标结果确认单"
    		      border="surround"
    		      style="width: 100%"
    					billStatus="1,2"
    		      suffixIcon="arrow-down-fill"
    		      :suffixIconStyle="{ color: '#B2B2B2' }"
    		    />
    		  </u-form-item>
    		</view>
    		
    		<view v-show="model.procurementType == '2'">
    		  <u-form-item label="关联单据" prop="associationBillId" required>
    		    <h-select-purchase-apply-form-contract-input-popup
    		      v-model="model.associationBillId"
							disabled
    		      placeholder="请关联采购申请单"
    		      border="surround"
    		      style="width: 100%"
    		      suffixIcon="arrow-down-fill"
    		      :suffixIconStyle="{ color: '#B2B2B2' }"
    		    />
    		  </u-form-item>
    		</view>
    		<view v-show="model.procurementType == '3'">
    		  <u-form-item label="关联单据" prop="associationBillId" required>
    		    <h-select-purchasing-requisition-input-popup
							disabled
    		      v-model="model.associationBillId"
    		      placeholder="请关联招标采购申请单"
    		      border="surround"
    		      style="width: 100%"
    		      suffixIcon="arrow-down-fill"
    		      :suffixIconStyle="{ color: '#B2B2B2' }"
    		    />
    		  </u-form-item>
    		</view>
    		
        <u-form-item label="签订日期" prop="signingDate" required>
          <h-time-select
            mode="datetime"
						disabled
            v-model="model.signingDate"
            placeholder="请选择签订日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
				<u-form-item label="定点合同" prop="isFixedTime" required>
				  <h-select-input-tag
				    class="w-100"
						disabled
				    v-model="model.isFixedTime"
				    objectField="model.isFixedTime"
				    placeholder="请选择定点合同"
				    border="surround"
				  	suffixIcon="arrow-down-fill"
				  	:suffixIconStyle="{ color: '#B2B2B2' }"
				    dictName="yn"
				  ></h-select-input-tag>
				</u-form-item>
				<view v-if="model.isFixedTime == 1">
					<u-form-item label="到期日期" prop="expireTime" required>
					  <h-time-select
					    mode="datetime"
							disabled
					    v-model="model.expireTime"
					    placeholder="请选择到期日期"
					    border="surround"
					    suffixIcon="calendar-fill"
					    :suffixIconStyle="{ color: '#B2B2B2' }"
					  ></h-time-select>
					</u-form-item>
				</view>
        <u-form-item label="合同总额(元)" prop="totalAmount">
    			<h-money-input
    				disabled
    				placeholder="请输入合同总额"
    				v-model="model.totalAmount"
    			></h-money-input>
        </u-form-item>
        <u-form-item label="发票类型" prop="invoiceCategory" required>
          <h-select-input-tag
            class="w-100"
						disabled
            v-model="model.invoiceCategory"
            objectField="model. invoiceCategory"
            placeholder="请选择发票类型"
            border="surround"
            dictName="invoice_type"
    				suffixIcon="arrow-down-fill"
    				:suffixIconStyle="{ color: '#B2B2B2' }"
            @change="invoiceCategoryBlur"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="税率(%)" prop="taxRate" required style="position: relative">
          <u--input type="number" disabled placeholder="请输入税率" v-number-normal v-model="model.taxRate" @blur="inputTaxRateBlur" />
          <span class="percent" style="position: absolute; right: 1em; color: rgb(178, 178, 178);">%</span>
        </u-form-item>
        <u-form-item label="税费(元)" prop="expensesTaxation" required>
          <!-- <u--input disabled type="number" placeholder="请输入税费" v-number-normal v-model="model.expensesTaxation" /> -->
    			<h-number-input disabled placeholder="请输入税费" v-model="model.expensesTaxation" :digit="2" :min="0"></h-number-input>
        </u-form-item>
        <!-- <u-form-item label="货期单位" prop="deliveryTimeUnit" required>
          <h-select-input-tag
            class="w-100"
            v-model="model.deliveryTimeUnit"
            objectField="model.deliveryTimeUnit"
            placeholder="请选择货期单位"
            border="surround"
    				suffixIcon="arrow-down-fill"
    				:suffixIconStyle="{ color: '#B2B2B2' }"
            dictName="period_validity_unit"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="货期" prop="deliveryTime" required>
          <u--input type="number" placeholder="请输入货期" v-number-normal v-model="model.deliveryTime" />
        </u-form-item>
        <u-form-item label="运输方式" prop="modeTransportation" required>
          <h-select-input-tag
            class="w-100"
            v-model="model.modeTransportation"
            objectField="model.modeTransportation"
            placeholder="请选择运输方式"
            border="surround"
    				suffixIcon="arrow-down-fill"
    				:suffixIconStyle="{ color: '#B2B2B2' }"
            dictName="transportation_type"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="运输费承担方" prop="trafficExpense" required>
          <h-select-input-tag
            class="w-100"
            v-model="model.trafficExpense"
            objectField="model.trafficExpense"
            placeholder="请选择运输费承担方"
            border="surround"
    				suffixIcon="arrow-down-fill"
    				:suffixIconStyle="{ color: '#B2B2B2' }"
            dictName="transportation_bearer"
          ></h-select-input-tag>
        </u-form-item> -->
        <u-form-item label="费用所属团队" prop="teamId" required>
          <h-select-team-input-popup
						disabled
            style="width: 100%"
            v-model="model.teamId"
            placeholder="请选择团队"
            :tdlx="1"
    				suffixIcon="arrow-down-fill"
    				:suffixIconStyle="{ color: '#B2B2B2' }"
            border="surround"
            @change="teamBack"
          ></h-select-team-input-popup>
        </u-form-item>
        <u-form-item label="是否工程类" prop="isEngineering" required>
          <h-select-input-tag
            class="w-100"
						disabled
            v-model="model.isEngineering"
            objectField="model.isEngineering"
            placeholder="请选择是否工程类"
    				suffixIcon="arrow-down-fill"
    				:suffixIconStyle="{ color: '#B2B2B2' }"
            border="surround"
            dictName="YES_OR_NO"
          ></h-select-input-tag>
        </u-form-item>
    		<u-form-item label="是否用印" prop="isUseSeal" required>
    		  <h-select-input-tag
    		    class="w-100"
						disabled
    		    v-model="model.isUseSeal"
    		    objectField="model.isUseSeal"
    		    placeholder="请选择是否用印"
    		    border="surround"
    				suffixIcon="arrow-down-fill"
    				:suffixIconStyle="{ color: '#B2B2B2' }"
    		    dictName="yn"
    				@change="handleRules"
    		  ></h-select-input-tag>
    		</u-form-item>
    		<template v-if="model.isUseSeal == '1'">
    			<u-form-item label="用印类型" prop="signSealWay" required>
    			  <h-select-input-tag
    			    class="w-100"
							disabled
    			    v-model="model.signSealWay"
    			    objectField="model.signSealWay"
    			    placeholder="请选择用印类型"
    					suffixIcon="arrow-down-fill"
    					:suffixIconStyle="{ color: '#B2B2B2' }"
    			    border="surround"
    			    dictName="seal_way"
    					@change="handleSignSealWay"
    			  ></h-select-input-tag>
    			</u-form-item>
    			<template v-if="model.isUseSeal == '1' && model.signSealWay == 'online'">
    				<u-form-item label="对方是否电子签章" prop="isSignSeal" required>
    					<h-dict-radio v-model="model.isSignSeal" disabled dictName="yes_no" @input="isSignSealInput"></h-dict-radio>
    				</u-form-item>
    				<u-form-item v-if="model.isSignSeal && model.isSignSeal == 1" label="对方盖章人" prop="supplyPsnName" required>
    					<u--input v-model="model.supplyPsnName" disabled placeholder="请输入对方盖章人"></u--input>
    				</u-form-item>
    				<u-form-item v-if="model.isSignSeal && model.isSignSeal == 1" label="联系方式" prop="supplyPsnMobile" required>
    					<u--input v-model="model.supplyPsnMobile" disabled placeholder="请输入联系方式"></u--input>
    				</u-form-item>
    			</template>
    		  <u-form-item label="印章类型" prop="sealType" required>
    		    <!-- <h-select-input-tag-multi-popup
    		      class="w-100"
    		      v-model="model.sealType"
    		      objectField="model.sealType"
    		      placeholder="请选择印章类型"
    		      border="surround"
    					suffixIcon="arrow-down-fill"
    					:suffixIconStyle="{ color: '#B2B2B2' }"
    		      dictName="yzlx_type"
    		    ></h-select-input-tag-multi-popup> -->
    				<h-dict-multi-select
    					v-model="model.sealType"
							disabled
    					style="width: 100%" 
    					placeholder="请选择印章类型"
    					dictName="yzlx_type"
    					border="surround"
    					suffixIcon="arrow-down-fill"
    					:suffixIconStyle="{color: '#B2B2B2'}"
    				></h-dict-multi-select>
    		  </u-form-item>
    		  <u-form-item label="用印份数" prop="useSealNumber" required>
    				<h-number-input placeholder="请输入用印份数" disabled v-model="model.useSealNumber" :digit="0" :min="1"></h-number-input>
    		  </u-form-item>
    		</template>
      </view>
    
      <view class="basic-style">
        <view class="basic-title basic-border pt-1">需方信息</view>
        <u-form-item label="公司名称" prop="demandCompanName" required>
          <h-select-company-input-popup
            style="width: 100%"
						disabled
            v-model="model.demandCompanName"
            border="surround"
            placeholder="请选择公司名称"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            @change="demandCompanNameInput"
          ></h-select-company-input-popup>
        </u-form-item>
    		<template v-if="model.isUseSeal == '1' && model.signSealWay == 'online'">
    			<u-form-item label="我方经办人" prop="psnName" required>
    				<u--input  v-model="model.psnName" disabled placeholder="请输入我方经办人"></u--input>
    			</u-form-item>
    			<u-form-item label="联系方式" prop="psnMobile" required>
    				<u--input  v-model="model.psnMobile" disabled placeholder="请输入联系方式"></u--input>
    			</u-form-item>
    		</template>
      </view>
    	
      <view class="basic-style">
        <view class="basic-title basic-border pt-1">其他信息</view>
				<u-form-item label="备注" prop="remark">
					<!-- #ifdef H5 -->
					<u--textarea v-model="model.remark" disabled confirm-type="done" maxlength="500" placeholder="请输入备注" />
					<!-- #endif -->
					<!-- #ifndef H5 -->
					<u--textarea v-model="model.remark" disabled :confirm-type="null" maxlength="500" count placeholder="请输入备注" />
					<!-- #endif -->
				</u-form-item>
      </view>
    
      <view class="basic-style">
        <view class="basic-title basic-border basic-flex">
    			<text>付款信息</text>
    			<view class="trip-form-notice">合同总额: {{ totalMoney }}元</view>
    		</view>
        <!-- <view class="space-y-1 py-1">
          <u-button size="small" type="primary" @click="addPaymentForm">新增</u-button>
        </view> -->
        <view class="trip-form-data">
    			<view v-for="(item, index) in paymentFormData" :key="index">
    				<PaymentFormInfo
							:disabled="true"
    					:item="item"
    					:index="index"
    					@edit="handleEditPaymentForm"
    					@remove="handleRemovePaymentForm"
    				/>
    			</view>
        </view>
        <u-popup mode="bottom" :show="showPaymentForm">
          <PaymentForm ref="dataPaymentForm" :index="index" @submit="handlePaymentFormSubmit" @close="closePaymentForm" />
        </u-popup>
      </view>
    
      <view class="basic-style">
        <view class="basic-title basic-border">物料信息</view>
        <!-- <view class="space-y-1 py-1"> -->
          <!-- <u-button size="small" type="primary" @click="addMaterialForm">新增</u-button> -->
    			<!-- <u-button size="small" type="primary" :disabled="isDisabled" :plain="true" @click="handleBalize">导入定标单关联采购物料清单</u-button> -->
    			<!-- <u-button size="small" type="primary" :plain="true" @click="handleMenu">导入采购清单</u-button> -->
    			<!-- <view style="display: flex;align-items: center;">
    				<u-button size="small" type="primary" :disabled="!deleteCheck.length" :plain="true" @click="deleteAllMaterial">批量删除</u-button>
    				<u-checkbox-group style="margin-left: 40rpx;" v-model="materialChecked" @change="handleCheck">
    					<u-checkbox :disabled="!isDisabled"></u-checkbox>
    				</u-checkbox-group>
    			</view> -->
        <!-- </view> -->
    		<view class="trip-form-data">
    			<view v-for="(item, index) in materialFormData" :key="index">
    				<MaterialFormInfo
    					:disabled="true"
    					:item="item"
    					:index="index"
    					@edit="handleEditMaterialForm"
    					@remove="handleRemoveMaterialForm"
    				>
    					<!-- <template slot="check">
    						<u-checkbox
    							:name="item.id"
    							:checked="item.checked"
    						>
    						</u-checkbox>
    					</template> -->
    				</MaterialFormInfo>
    			</view>
    		</view>
        <u-popup mode="bottom" :show="showMaterialForm" :closeOnClickOverlay="false">
          <MaterialForm ref="dataMaterialForm" :index="index" @submit="handleMaterialFormSubmit" @close="closeMaterialForm" />
        </u-popup>
      </view>
    	<view class="basic-style"  v-if="model.isUseSeal == 1">
    	  <view class="basic-title basic-border">用印文件<span style="color: #faad14;font-weight: 600">（请上传只需盖章的用印文件！）</span></view>
    	  <u-form-item label="用印文件" prop="signFile" required>
    			<view class="py-1 space-y-1" style="width: 100%">
    				<file-list v-model="model.signFile"></file-list>
    			</view>
    		</u-form-item>
    	</view>
    	<view class="basic-style">
    	  <view class="basic-title basic-border">合同原件扫描件(仅合同管理员上传)</view>
    	  <view class="py-1 space-y-1" style="width: 100%">
    	    <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
    	    <h-upload-file v-model="model.contractOrgFile" :isIcon="false" fileType=".pdf, .PDF"></h-upload-file>
    	    <file-list v-if="model.contractOrgFile" v-model="model.contractOrgFile" :isDelete="true"></file-list>
    	  </view>
    	</view>
      <view class="basic-style">
        <view class="basic-title basic-border">相关附件</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <file-list v-model="model.purchaseFile"></file-list>
        </view>
      </view>
    	
    	<view class="space-x-1 px-1 btn_position">
    		<backButton  @onSubmit="onSubmit" :nodeObj="nodeObj" :model="dataForm" :resultObj="resultObj"></backButton>
    	</view>
    	<view style="height: 100rpx"></view>
    </u-form>
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
// import {
//   gainBillNo,
//   add,
//   info,
//   edit,
//   queryPurchaseSupplierById,
//   queryRelReimbursementBillId,
//   queryPurchaseContractById,
//   queryProjectContractById,
// } from '@/api/finance/ErpFinancePaymentSlipForm'
import { mapState } from 'vuex'
import moment from 'moment'
import backButton from '@/components/backButton.vue'
import { gainBillNo, add, info,edit,urlListDetail } from '@/api/contract/ErpPurchaseContractForm'
import {
  queryByIdPurchaseContractSuppliesAllList, // 物料信息
	queryByIdPurchaseContractPayAllList, // 付款信息
} from '@/api/index'
import { initDictOptions, filterMultiDictText } from '@/utils/JDictSelectUtil.js'
import {getProcessTaskTransInfo} from '@/api/index.js' // 流程流转
import fileList from '@/pages/synergy/components/fileList.vue'
import PaymentForm from '@/pages/contract/components/PaymentForm.vue'
import PaymentFormInfo from '@/pages/contract/components/PaymentFormInfo.vue'

import applyFormInput from '@/pages/contract/components/applyFormInput.vue'
import cannibalizeInput from '@/pages/contract/components/cannibalizeInput.vue'
import MaterialForm from '@/pages/contract/components/MaterialForm.vue'
import MaterialFormInfo from '@/pages/contract/components/MaterialFormInfo.vue'
import Decimal from 'decimal.js'
export default {
  name: 'ErpPurchaseContractFormBack',
  components: {
		fileList,
		PaymentForm,
		PaymentFormInfo,
		backButton,
    MaterialForm,
    MaterialFormInfo,
		applyFormInput,
		cannibalizeInput,
	},
  data() {
    return {
			resultObj: {}, // 流程图流转信息
			dataForm: {},
			nodeObj: {},
			tabvalue: '',
			
      dictOptions: {},
      contentflag: false,
      isSubmit: false,
      backUpApplyCompany: '',
      backUpTeamId: '',
      isReset: false,
      resetKey: '',
      basicForm: {},
      index: null,
      showFormModal: false,
      // confirmModal: false,
			
			
			
			teamIdBackups: null,
			materialChecked: [],
			deleteCheck: [],
			confirmModal: false,
			id: '',
			basicPaymentForm: {},
			basicFormB: {},
			basicMaterialForm: {},
			showPaymentForm: false,
			showFormModalB: false,
			showMaterialForm: false,
			paymentFormData: [],
			materialFormData: [],
			model: {
			// 基本信息 - 公用
			bpmBizTitle: '',
			purchaseBill: '',
			proposer: '',
			proposerDeptId: '',
			createTime: '',
			// 基本信息 - 非公用
			masterCopy: null,
			bchte: '',
			htlx: 2,
			procurementType: '',
			signSealWay: '',
			supplyPsnName: '',
			psnName: '',
			supplyPsnMobile: '',
			psnMobile: '',
			// 附件
			purchaseFile: null,
			signFile: null
			},
			rules: {
				purchaseBill: [{ required: true, message: '请输入单据编号!', trigger: ['blur', 'change'] }],
				proposerDeptId: [{ required: true, message: '请选择申请部门!', trigger: ['blur', 'change'] }],
				proposer: [{ required: true, message: '请选择申请人!', trigger: ['blur', 'change'] }],
				createTime: [{ required: true, message: '请选择申请时间!', trigger: ['blur', 'change'] }],
				signingDate: [{ required: true, message: '请选择签订日期!', trigger: 'change' }],
				isFixedTime: [{ required: true, message: '请选择定点合同!', trigger: 'change' }],
				expireTime: [{ required: true, message: '请选择到期日期!', trigger: 'change' }],
			    taxRate: [
			      { required: true, message: '请输入税率!', trigger: 'blur' },
			      { required: true, pattern: /^(([0-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的税率!' },
			    ],
			    expensesTaxation: [
			      { required: true, message: '请输入税费!', trigger: 'blur' },
			      { required: true, pattern: /^(([0-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' },
			    ],
			    invoiceCategory: [{ required: true, message: '请选择发票类型!', trigger: 'blur' }],
			    deliveryTime: [
			      { required: true, message: '请输入货期!', trigger: 'blur' },
			      { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正整数!' },
			    ],
			    teamId: [{ required: true, message: '请选择费用所属团队!', trigger: 'change' }],
			    demandCompanName: [{ required: true, message: '请选择需方公司名称!', trigger: 'change' }],
			    supplyCompanName: [{ required: true, message: '请选择供方公司名称!', trigger: 'change' }],
			    supplyCompanyAddress: [{ required: true, message: '请输入供方公司地址!', trigger: 'blur' }],
			    supplyEntrustedAgent: [{ required: true, message: '请输入供方委托代理人!', trigger: 'blur' }],
			    supplyPhoneNumber: [
			      { required: true, message: '请输入供方手机号码!', trigger: 'blur' },
			      { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码!',trigger: ['blur','change'] },
			    ],
			    supplyBankName: [{ required: true, message: '请输入供方开户银行!', trigger: 'blur' }],
			    supplyBankAccountNo: [
			      { required: true, message: '请输入供方银行账号!', trigger: 'blur' }
			    ],
			    supplyRegistrationNumber: [{ required: true, message: '请输入供方纳税人识别号!', trigger: 'blur' }],
			    isProject: [{ required: true, message: '请选择是否关联项目!', trigger: 'blur' }],
			    isEngineering: [{ required: true, message: '请选择是否工程类!', trigger: 'blur' }],
					isUseSeal: [ { required: true, message: '请选择是否用印!', trigger: ['blur', 'change'] } ],
					signSealWay: [ { required: true, message: '请选择用印类型!', trigger: ['blur', 'change'] } ],
					isSignSeal: [ { required: true, message: '请选择对方是否电子签章!', trigger: ['blur', 'change'] } ],
					supplyPsnName: [ { required: true, message: '请输入人员姓名!', trigger: ['blur'] } ],
					supplyPsnMobile: [
						{ required: true, message: '请输入联系方式!' },
						{ pattern: /(^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$)|(^\/$)/, message: '请输入正确的联系方式!', trigger: ['blur', 'change'] }
					],
					psnName: [ { required: true, message: '请输入人员姓名!', trigger: ['blur'] } ],
					psnMobile: [
						{ required: true, message: '请输入联系方式!' },
						{ pattern: /(^1\d{10}$|^(0\d{2,3}-?|\(0\d{2,3}\))?[1-9]\d{4,7}(-\d{1,8})?$)|(^\/$)/, message: '请输入正确的联系方式!', trigger: ['blur', 'change'] }
					],
			    contractName: [{ required: true, message: '请输入合同名称!', trigger: 'blur' }],
			    procurementType: [{ required: true, message: '请选择采购类型!', trigger: ['blur', 'change'] }],
					signFile: [{ required: false, message: '请上传用印文件!' }],
					applyTeam: [{ required: true, message: '请选择申请人所属团队!' }],
			  },
      itemList: [], //信息费用单
    }
  },
  onLoad(options) {
    this.dataForm = JSON.parse(decodeURIComponent(options.item))
    var that = this
    // #ifdef APP-NVUE
    var eventChannel = this.$scope.eventChannel // 兼容APP-NVUE
    // #endif
    // #ifndef APP-NVUE
    var eventChannel = this.getOpenerEventChannel()
    // #endif
    // 监听sendMessage事件，获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on('sendMessage', function (data) {
  		that.nodeObj = JSON.parse(decodeURIComponent(data.nodeObj))
  		that.id = that.nodeObj.dataId
      that.tabvalue = data.tabvalue
      that.initInfo()
  		that.getProcessTaskTrans(that.dataForm.id)
  		
    })
  },
  computed: {
    ...mapState(['userInfo']),
		totalMoney() {
		  return this.paymentFormData.reduce((total, item) => total + Number(item.paymentAmount), 0).toFixed(2)
		},
		isDisabled: function () {
			if (this.materialFormData && this.materialFormData.length) {
				return true
			} else {
				return false
			}
		}
  },
  methods: {
		// 查询流程流转信息 -- 获取下一节点信息
		getProcessTaskTrans(taskId){
			getProcessTaskTransInfo({ taskId }).then(res => {
				if(res.success){
					this.resultObj = res.result
				} else {
					this.$refs.uToast.show({
						message: res.message,
						type: 'error'
					})
				}
			}).catch(err => {
				console.log(err);
			})
		},
		
		
		// 跳转到完善非正式供应商信息
		getUnSupplier(){
			
			uni.navigateTo({
				url:'/pages/purchase/components/unSupplierForm'
			})
			
		},
		onJudge(){
			// 保存返回的监听，事先处理好
			uni.$on("supplierBack", res => {
				
				this.supplyCompanBack(res)
				
				// 清除监听
				uni.$off('supplierBack');
			})
			
			uni.navigateTo({
				url:'/pages/common/selectSupplier/selectSupplierInput'
			})
		},
		handleCheck(detail){
			this.materialFormData.map(val => {
				val.checked = !!detail.length
				return val
			})
			if(detail.length){
				this.materialFormData.map((val,index) => {
					this.deleteCheck.push(val.id)
				})
			} else {
				this.deleteCheck = []
			}
			this.$forceUpdate()
		},
		childCheck(detail){
			this.deleteCheck = detail
			this.materialFormData.map(val => {
				val.checked = this.deleteCheck.includes(val.id)
				return val
			})
			if(detail.length == this.materialFormData.length){
				this.materialChecked = ['']
			} else {
				this.materialChecked = []
			}
			this.$forceUpdate()
		},
		deleteAllMaterial(){
			const that = this
			uni.showModal({
				content: '确定删除吗？',
				success: res => {
					if (res.confirm) {
						this.materialFormData = this.materialFormData.filter((i) => {
							return !this.deleteCheck.includes(i.id)
						})
						this.deleteCheck = []
						this.materialChecked = []
					}
				}
			});
		},
		// 数组对象去重
		arrHeavy (arr) {
			let newobj = {}
			arr = arr.reduce((preVal, curVal) => {
				newobj[curVal.materialBillId] ? '' : newobj[curVal.materialBillId] = preVal.push(curVal);
				return preVal
			}, [])
			return arr
		},
		contactBack(data){
			data.map(value => {
				this.materialFormData.push(value)
			})
			this.materialFormData = this.arrHeavy(this.materialFormData)
		},
		cannibalizeInputBack(val){
			urlListDetail({ calibrationId: val }).then((res) => {
			 if (res.success) {
					this.materialFormData = []
					this.materialFormData = res.result
				}
			})
		},
		handleBalize(){
			if(this.isDisabled) return
			this.$refs.cannibalizeInput.showPopup = true
		},
		handleMenu(){
			this.$refs.applyFormInput.showPopup = true
		},
		handleRules(val){
			if(this.model.isUseSeal == '1'){
				this.$set(this.rules,'sealType',[{ required: true, message: '请选择印章类型!' }])
				this.$set(this.rules,'useSealNumber',[
		      { required: true, message: '请输入用印份数!', trigger: 'blur' },
		      { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正整数!' },
		    ])
			} else {
				this.$delete(this.rules,'sealType')
				this.$delete(this.rules,'useSealNumber')
				this.$set(this.model,'sealType','')
				this.$set(this.model,'useSealNumber','')
				this.$set(this.model, 'signSealWay', '') // 置空电子签章
			}
		},
		
		// 选择电子签章
		handleSignSealWay (val) {
			if (val == 'online') {
				this.rules.signFile[0].required = true
			} else {
				this.rules.signFile[0].required = false
			}
			this.$set(this.model, 'isSignSeal', '0') // 对方是否电子签章默认为否
			this.$set(this.model, 'psnName', '')
			this.$set(this.model, 'psnMobile', '')
			this.$set(this.model, 'supplyPsnName', '')
			this.$set(this.model, 'supplyPsnMobile', '')
		},
		// 点击对方是否为电子签章
		isSignSealInput () {
			this.$set(this.model, 'supplyPsnName', '')
			this.$set(this.model, 'supplyPsnMobile', '')
		},
		// 需方选择往来单位
		demandCompanNameInput(dataBack) {
		  // this.$refs.form.clearValidate('demandCompanyAddress')
		  // this.$refs.form.clearValidate('demandRegistrationNumber')
		  // this.$refs.form.clearValidate('demandBankName')
		  // this.$refs.form.clearValidate('demandBankAccountNo')
		  if (dataBack) {
		    this.$set(this.model, 'demandCompanyAddress', dataBack.enterpriseAddress) // 公司地址
		    this.$set(this.model, 'demandRegistrationNumber', dataBack.enterpriseCreditCode) // 纳税人识别号
		    this.$set(this.model, 'demandBankName', dataBack.bankName) // 开户行
		    this.$set(this.model, 'demandBankAccountNo', dataBack.bankAccountNo) // 银行账户
		  } else {
		    this.$set(this.model, 'demandCompanyAddress', null) // 公司地址
		    this.$set(this.model, 'demandRegistrationNumber', null) // 纳税人识别号
		    this.$set(this.model, 'demandBankName', null) // 开户行
		    this.$set(this.model, 'demandBankAccountNo', null) // 银行账户
		  }
		},
		teamBack(item) {
		  if (!!this.model.teamId && item) {
		    if (this.teamIdBackups !== item.id && !!this.model.projectId) {
		      this.$set(this.model, 'projectId', null)
		    }
		    this.teamIdBackups = item.id
		  }
		},
		// 供方选择往来单位
		supplyCompanBack(dataBack) {
		
		// this.officialType = dataBack.officialType
		this.$set(this.model, 'supplyCompanName', dataBack.id) 
		
		  this.$set(this.model, 'supplyCompanyAddress', dataBack.enterpriseAddress) // 公司地址
		  this.$set(this.model, 'supplyBankName', dataBack.bankName) // 开户银行
		  this.$set(this.model, 'supplyBankAccountNo', dataBack.bankAccountNo) // 银行账号
		  this.$set(this.model, 'supplyRegistrationNumber', dataBack.enterpriseCreditCode) // 纳税人识别号
		},
		// 税率输入框变化时
		inputTaxRateBlur(value) {
		  let item = this.model.taxRate.toString().slice(0, 2)
		  let data = this.model.taxRate.toString().replace(/\b(0+)/gi, '')
		  if (this.model.invoiceCategory !== '0' && item !== '0.') {
		    // 去除0
		    var num = data
		  }
		  if (data == '.') {
		    this.$set(this.model, 'taxRate', null)
		  }
		  if (num >= 0 && num < 100) {
		    this.$set(this.model, 'taxRate', num)
		  }
		  if (num < 0) {
		    this.$set(this.model, 'taxRate', '0')
		  }
		  if (num >= 100) {
		    this.$set(this.model, 'taxRate', '100')
		  }
		  if (this.model.totalAmount) {
		    // 税费=合同额/（1+税率）* 税率
		    var money = new Decimal(this.model.totalAmount)
		      .div(new Decimal(1).add(new Decimal(this.model.taxRate).div(new Decimal(100))))
		      .mul(new Decimal(this.model.taxRate).div(new Decimal(100)))
		    this.$set(this.model, 'expensesTaxation', money.toFixed(2))
		  }
		  // this.$refs.form.clearValidate('expensesTaxation')
		},
		
		// 采购类型
		handleChangeProvisionType (val) {
			if (val == '1') {
				this.$set(this.rules, 'associationBillId', [{ required: true, message: '请选择关联单据!' }]);
				//清除采购申请单数据及校验
				this.$set(this.model, 'associationBillId', null);
			} else if (val == '2') {
				this.$set(this.rules, 'associationBillId', [{ required: true, message: '请选择关联单据!' }]);
				this.$set(this.model, 'associationBillId', null);
			}else if(val == '3'){
				this.$set(this.rules, 'associationBillId', [{ required: true, message: '请选择关联单据!' }]);
				//清除采购申请单数据及校验
				this.$set(this.model, 'associationBillId', null);
			}else {
				//清除关联单据ID数据及校验
				this.$set(this.model, 'associationBillId', null);
				this.$delete(this.rules, 'associationBillId');
			}
		},
		
		invoiceCategoryBlur(value) {
		  this.$refs.form.clearValidate('taxRate')
		  if (value == 0) {
		    this.$set(this.model, 'taxRate', '0')
		  } else {
		    this.$set(this.model, 'taxRate', null)
		  }
		  this.$set(this.model, 'expensesTaxation', '0')
		},
		calTotalMoney () {
			var money = 0
			if (!!this.paymentFormData && this.paymentFormData.length) {
				this.paymentFormData.map(item => {
				money = money + Number(item.paymentAmount)
			})
			} else {
				money = 0
			}
			return money.toFixed(2)
		},
		handleEditPaymentForm([item, index]) {
		  this.basicPaymentForm = { ...item }
		  this.index = index
		  this.showPaymentForm = true
			var ratioPayment = this.calculateRatioPayment() - Number(item.ratioPayment)
			this.$nextTick(() => {
				this.openPaymentForm(ratioPayment)
			})
		},
		handleRemovePaymentForm(item) {
		  this.paymentFormData = this.paymentFormData.filter((i) => i !== item)
		},
		closePaymentForm() {
		  this.$refs.dataPaymentForm.reset()
		  this.basicPaymentForm = {}
		  this.index = null
			this.showPaymentForm = false
		},
		openPaymentForm(value) {
			this.$refs.dataPaymentForm.basicForm = Object.assign({},this.basicPaymentForm)
			this.$nextTick(() => {
				this.$refs.dataPaymentForm.calculateRatioPayment(value)
			})
		},
		addPaymentForm() {
		  this.index = null
			this.basicPaymentForm = {}
		  this.showPaymentForm = true
			this.$nextTick(() => {
				this.openPaymentForm(this.calculateRatioPayment())
			})
		},
		handlePaymentFormSubmit([data, index]) {
		  this.showPaymentForm = false
		  if (typeof index === 'number') {
		    this.$set(this.paymentFormData, index, data)
		  } else {
		    this.paymentFormData.push(data)
		  }
			this.$set(this.model, 'totalAmount', this.calTotalMoney())
		},
		handleEditMaterialForm([item, index]) {
		  this.basicMaterialForm = { ...item }
		  this.index = index
		  this.showMaterialForm = true
			this.$nextTick(() => {
				this.openMaterialForm()
			})
		},
		handleRemoveMaterialForm(item) {
		  this.materialFormData = this.materialFormData.filter((i) => i !== item)
			this.$set(this.model, 'totalAmount', this.calTotalMoney())
		},
		closeMaterialForm() {
		  this.$refs.dataMaterialForm.reset()
		  this.basicMaterialForm = {}
		  this.index = null
			this.showMaterialForm = false
		},
		openMaterialForm() {
		  this.$refs.dataMaterialForm.basicForm = Object.assign({},this.basicMaterialForm)
			this.$refs.dataMaterialForm.firstClick = 1
			this.$refs.dataMaterialForm.provisionBroadChange()
		},
		addMaterialForm() {
		  this.index = null
			this.basicMaterialForm = {}
		  this.showMaterialForm = true
		},
		handleMaterialFormSubmit([data, index]) {
		  this.showMaterialForm = false
		  if (typeof index === 'number') {
		    this.$set(this.materialFormData, index, data)
		  } else {
		    this.materialFormData.push(data)
		  }
			if(!this.deleteCheck.includes(data.id)){
				this.materialChecked = []
			}
		},
		// 初始化新增需要的数据
		initForm() {
		  this.model.proposer = this.userInfo.empId //当前登录人
		  this.model.proposerDeptId = this.userInfo.deptId //当前登录人部门
		  this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
			this.$set(this.model, 'deliveryTimeUnit', '3')
		},
		async initInfo() {
		  const response = await info({ id: this.id })
		  const data = response?.result || {}
		  this.model = Object.assign({}, data)
			if (this.model && this.model.isUseSeal !== null) {
				this.model.isUseSeal = this.model.isUseSeal + ''
			}
			const resA = await queryByIdPurchaseContractPayAllList({ billId: this.model.id })
			this.paymentFormData = resA.result.records || resA.result
			const resB = await queryByIdPurchaseContractSuppliesAllList({ billId: this.model.id })
			this.materialFormData = resB.result.records || resB.result
			this.handleRules(this.model?.isUseSeal)
			const keys = ['expensesTaxation','sfyz','taxRate']
			keys.forEach(val => {
				if(typeof this.model[val] == 'number'){
					this.model[val] = String(this.model[val])
				}
			})
		},
		// 计算付款比例
		calculateRatioPayment () {
			var ratioPayment = 0
			if (this.paymentFormData && this.paymentFormData.length) {
				this.paymentFormData.map(value => {
					ratioPayment = Number(value.ratioPayment) - 0 + Number(ratioPayment)
				})
			}
			return ratioPayment
		},
		validateForm() {
		  return this.$refs.form.validate().then(async () => {
		    if (this.paymentFormData.length === 0) {
		      this.$u.toast('请添加付款信息！')
		      return Promise.reject()
		    }
				
				if (this.calculateRatioPayment() < 100) {
				  this.$u.toast('付款信息中付款比例之和没有达到100%！')
				  return Promise.reject()
				}
				
				if (this.materialFormData.length === 0) {
				  this.$u.toast('请添加物料信息！')
				  return Promise.reject()
				}
				
				for (var i = 0; i < this.materialFormData.length; i++) {
					if (!this.materialFormData[i].unitPrice) {
						this.$u.toast('请输入物料信息单价！');
						return Promise.reject()
					}
				}
				
		    if (!this.model.deliveryTimeUnit) {
					this.$u.toast('请选择货期单位！');
					return Promise.reject()
				}
				if (!this.model.contractOrgFile) {
					this.$u.toast('请上传合同原件扫描件！');
					return Promise.reject('请上传合同原件扫描件！')
				}
		    
		    return Promise.resolve()
		  })
		},
    
    async onSubmit() {
      await this.validateForm()
      try {
        var url = ''
        if (this.id) {
          url = edit
        } else {
          url = add
        }
        // this.model.itemList = this.itemList
				let _this = this
        const response = await url({
          ...this.model,
					purchaseContractPayments: this.paymentFormData,
					purchaseContractSupplies: this.materialFormData,
        })
        if (response.success) {
          this.$refs.uToast.show({
          	message: '提交成功',
          	type: 'success',
          	complete () {
          		_this.onAudit()
          	}
          })
          this.isSubmit = true
        } else {
          this.$refs.uToast.show({
            message: response.message,
            type: 'error',
          })
        }
      } finally {
				// error
      }
    },
    onAudit() {
      if (!this.isSubmit) {
        uni.showToast({
          title: '请完善表单后审核',
          icon: 'none',
        })
        return false
      }
      var that = this
      uni.navigateTo({
        url: '/pages/synergy/erpPurchaseContractList' + `?item=${encodeURIComponent(JSON.stringify(this.dataForm).replace(/%/g, '%25'))}`,
        events: {
          // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
          // acceptDataFromOpenedPage: function(data) {
          // }
        },
        success: function (data) {
          // 通过eventChannel向被打开页面传送数据
          var params = {
            nodeObj: encodeURIComponent(JSON.stringify(that.nodeObj).replace(/%/g, '%25')),
            tabvalue: that.tabvalue,
          }
          data.eventChannel.emit('sendMessage', params)
        },
        fail: function (err) {
          this.$refs.uToast.show({
            message: '请联系管理员配置',
            type: 'error',
          })
        },
      })
    }
  },
  watch: {
  	// 监听税费
  	'model.totalAmount': {
  		handler (val) {
  			this.$nextTick(() => {
  				if (val && this.model.taxRate) {
  					// 税费=合同额/（1+税率）* 税率
  					var money = new Decimal(this.model.totalAmount).div(new Decimal(1).add(new Decimal(this.model.taxRate).div(new Decimal(100)))).mul(new Decimal(this.model.taxRate).div(new Decimal(100)))
  					this.$set(this.model, 'expensesTaxation', money.toFixed(2))
  				} else {
  					this.$set(this.model, 'expensesTaxation', '0')
  				}
  			})
  		},
  		immediate: true,
  		deep: true
  	}
  },
}
</script>

<style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
.trip-form-data {
  margin: 6px 0;
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
</style>
